package xin.lms.model;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonFormat;
import eu.bitwalker.useragentutils.UserAgent;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import xin.core.jpa.JpaConstant;
import xin.core.jpa.model.AutoDateUUIDEntity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * <pre>
 * 系统访问日志
 * </pre>
 *
 * @author lixin@outlook.com
 * @version 1.0
 * @since 2017/11/26 13:40
 */
@Entity
@Table(name = "sys_access_log")
@EqualsAndHashCode(callSuper = true)
@Data
@ToString
@ApiModel
public class AccessLog extends AutoDateUUIDEntity {
    /**
     * 用户姓名 登录成功根据userId查出，传值用，不存
     */
    @ApiModelProperty(value = "用户姓名")
    @Column(length = JpaConstant.CommonStringMidLength)
    private String userName;

    /**
     * 登录时间
     */
    @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
    @ApiModelProperty(value = "登录时间")
    @Column()
    private Date loginTime;

    /**
     * 登出时间
     */
    @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
    @ApiModelProperty(value = "登出时间")
    @Column
    private Date logoutTime;

    /**
     * 地区
     */
    @ApiModelProperty(value = "地区")
    @Column(length = JpaConstant.CommonStringMidLength)
    private String region;

    /**
     * 登录IP
     */
    @ApiModelProperty(value = "登录IP")
    @Column(length = JpaConstant.IP)
    private String ipAddr;


    /**
     * 详情
     */
    @ApiModelProperty(value = "详情")
    @Column(length = JpaConstant.DescriptionColumnLength)
    private String detail;

    public void initDetail(HttpServletRequest request){
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        JSONObject obj =  new JSONObject();
        obj.put("remoteHost",request.getRemoteHost());
        obj.put("remotePort",request.getRemotePort());
        obj.put("remoteUser",request.getRemoteUser());
        obj.put("requestURI",request.getRequestURI());
        obj.put("servletPath",request.getServletPath());
        obj.put("serverName",request.getServerName());
        obj.put("serverPort",request.getServerPort());
        obj.put("requestMethod",request.getMethod());
        obj.put("httpAacceptLanguage",request.getHeader("accept-language"));
        obj.put("httpReferer",request.getHeader("Referer"));
        obj.put("browser",userAgent.getBrowser());
        obj.put("os",userAgent.getOperatingSystem());
        this.detail =  obj.toJSONString();
    }
}